package com.turbo.boot.crawler.spider.worker.impl.quota;

import com.alibaba.fastjson.JSON;
import com.turbo.boot.crawler.dao.dal.CrawlerResultDal;
import com.turbo.boot.crawler.dao.entity.CrawlerResultEntity;
import com.turbo.boot.crawler.spider.worker.BaseTurboApiCrawlerPageParser;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 描述
 *
 * @author wuyn
 * @since 2024/4/19
 */
@Service("mysteelCrawlerPageParser")
public class MysteelCrawlerPageParser extends BaseTurboApiCrawlerPageParser<MysteelCrawlerPageParser.PageVo> {


    @Resource
    private CrawlerResultDal crawlerResultDal;

    @Override
    public void parse(PageVo pageVo) {
        // 解析封装 PageVo 对象
        if (StringUtils.isEmpty(pageVo.getQuotaCode())) {
            return;
        }

        List<CrawlerResultEntity> batch = new ArrayList<>();
        int length = pageVo.getXzValues().size();
        for (int i = 0; i < length; i++) {

            CrawlerResultEntity entity = buildCrawlerResultEntity();
            entity.setQuotaCode(pageVo.getQuotaCode());
            entity.setQuotaName(pageVo.getQuotaName());
            entity.setQuotaValue(pageVo.getYzValues().get(i));

            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
            DateTime dateTime = formatter.parseDateTime(pageVo.getXzValues().get(i));
            // 如果需要转换为java.util.Date
            Date utilDate = dateTime.toDate();

            entity.setCollectedAt(utilDate);

            batch.add(entity);
        }

        if (CollectionUtils.isNotEmpty(batch)) {
            crawlerResultDal.insertBatch(batch);
        }

        System.out.println(pageVo.toString());
    }


    @Setter
    @Getter
    public static class PageVo {
        String quotaCode;
        String quotaName;
        List<String> xzValues;
        List<String> yzValues;

        @Override
        public String toString() {
            return JSON.toJSONString(this);
        }
    }
}
